package com.javademo.multithreadingtest;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SynchronizedMethodsTest {
    public static void main(String[] args) {
        Counter counter1 = new Counter();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 100000; i++) {
                counter1.add();
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 99999 + 1; i++) {
                counter1.delete();

            }
        });
        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            log.info(e.getMessage());
        }
        log.info("count:{}", counter1.getCount());
    }
}

@Getter
@Slf4j
class Counter {
    private int count;

    public synchronized void add() {
        count++;
        log.info("Thread 1 is running");
    }

    public synchronized void delete() {
        count--;
        log.info("Thread 2 is running");
    }
}
